//index.js
//获取应用实例
const app = getApp()
const api = require("../../utils/interface.js")
const math = require("../../utils/math.js")
const tools = require("../../utils/util.js")
Page({
  data: {
    statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
    storeId:"",
    storeList:[],
    orderList:[],//滚动效果
    storeName:"",//门店名称
    distance:"",//距离
    active:"",//活动名称
    oilnum:"",//油品号
    time:"",//营业时间
    cheapmoney:"",//补贴金额
    money:"",//油价
    distanceInfo:{lat:'',lot:''},
    bannerDTOList:[],//首页轮播
    formType:0,
    shopData:null,
    textad:"",//首页优惠活动
    checkSwitch:"",
    cityName:"",
    cityId:"",
    showRegisterState:false,
    activity:"",
    regesterData:[],
    registerActivetyMoney:0,
    memberState:false,
    result:""//删除
  },
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
  },
  catchTouchMove: function (res) {
    return false
  },
  // 后加
  scancode: function () {
    let that = this;
    wx.scanCode({
      success: (res) => {
        let str = res.path.split('=')[1]
          wx.navigateTo({
            url: '/pages/nextY/nextY?scene=' + str
          })
      }
    })
  },
  goggggg(){
    wx.navigateTo({
      url: '/pages/loginOut/loginOut',
    })
  },
  onShow(){   
    if (this.data.formType==1){
      wx.setStorageSync('cityId', this.data.cityId)
      this.data.formType = 0
    }
    getApp().login().then(res => {
      // 会员是否锁定
      if (getApp().globalData.flag) {
        this.setData({
          memberState: true
        })
      }
      let cityId = wx.getStorageSync('cityId')
      this.drivingDistance(cityId)
      // if (res && res.data.loginCount <= 1) {
      //   this.registerActivityState(res)
      // }
    })
    this.getShopList()
    // let state = wx.getStorageSync('indexSubCardState')
    // if (!state){
    //   this.receiveSub()
    // }
  },
  // 油站详情
  goStationInfo(){    
    if (!this.data.storeId){
      return false
    }
      wx.navigateTo({
        url: '/pages/webView/webview?url=' + getApp().globalData.url + 'stationInfo&stationId=' + this.data.storeId+'&lat=' + this.data.distanceInfo.lat + '&lot=' + this.data.distanceInfo.lot,
      })
  },
  //跳转到一键加油
  goOil(){
    if (this.data.checkSwitch=='0'){
      wx.showModal({
        title: '提示',
        content: '该站点暂不支持点我加油',
        showCancel:false
      })
      return false
    }
    let that = this
    if (that.data.storeId== '1') {
      getApp().globalData.fundebug.notify("油站id为1-1000", that.data.storeId);
    }
    // + that.data.storeId
    wx.navigateTo({
      url: '../nextY/nextY?storeid=1' 
    })
  },
  //接口获取最近油站
  drivingDistance(cityid) {
    let that=this
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        that.data.distanceInfo.lat = res.latitude
        that.data.distanceInfo.lot = res.longitude
        that.getHomeData(res.latitude, res.longitude, cityid)
      },
      fail(err){
        wx.hideLoading()
        wx.getSetting({
          success(res) {
            if (res.authSetting["scope.userLocation"] == false) {
              wx.showModal({
                title: '提示',
                content: '你的位置信息将用于小程序位置接口的效果展示',
                showCancel: false,
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success(res) {
                       }
                    })
                  }
                }
              })
            }else{
              wx.showModal({
                title: '提示',
                content: '定位失败，请检查手机位置/定位是否打开',
                showCancel:false
              })
            }
          }
        })
        
      }
    })
  },
  // 获取首页信息
  getHomeData(lat, lot, cityId) {
    let that = this
    let user = wx.getStorageSync('userInfo')
    api.indexPage({ lat, lot, memberId: user?user.id:'', cityId }).then(res => {
      console.log(res.data.result)
      wx.hideLoading()
      if (!res.data.result.cityStatus){
        wx.showModal({
          title: '提示',
          content: '当前城市未开通服务',
        })
        return false
      }
      this.data.cityId = res.data.result.cityId
      if (res.data.result.orderList && res.data.result.orderList.length){
        res.data.result.orderList.map((item, index) => {
          item.orderAmount = math.divide(item.orderAmount, 100).toFixed(2)
          // item.subsidy = math.divide(item.subsidy, 100).toFixed(2)
        })
      }
      const storeId = res.data.result.storeId
      const storeList = res.data.result
      const storeName = res.data.result.storeName
      const distance = math.divide(Number(res.data.result.distance), 1000).toFixed(2)
      const orderList = res.data.result.orderList
      const bannerDTOList = res.data.result.bannerDTOList
      const activityDTOList1 = res.data.result.activityDTOList
      const activityDTOList = res.data.result.activityBackgroundDTOList//轮播显示图片
      let textad = ""
      if (res.data.result.textAdvertDTOList){
         textad = res.data.result.textAdvertDTOList[0].name
      }
      
      const productInfo = res.data.result.productInfoStoreDTO
      let money = 0
      let cutPrice = 0
      if (productInfo) {
        money = math.divide(productInfo.plateformPrice, 100)//平台最低价
        cutPrice = math.divide(productInfo.cutPrice, 100)//补贴价
      }
      let activity = null
      if (bannerDTOList && bannerDTOList.length) {
        bannerDTOList.map(item => {
          if (item.bannerPosition == 3) {
            activity = item
          }
        })
      }
      that.setData({
        storeId,
        storeList,
        storeName,
        distance,
        orderList,
        textad,
        bannerDTOList,
        activityDTOList,
        money: money,
        cheapmoney: cutPrice,
        checkSwitch: res.data.result.checkSwitch,
        cityName: res.data.result.cityName,
        activity: activity
      })
    })
  },
  go_city(){
    wx.navigateTo({
      url: '/pages/webView/webview?url=' + getApp().globalData.url + '&lat=' + this.data.distanceInfo.lat + '&lot=' + this.data.distanceInfo.lot,
    })
  },
  // 获取更多的油站
  go_storeList(){
    let user = wx.getStorageSync('userInfo')
    let id = user ? user.id:""
    let cityId = wx.getStorageSync('cityId')||this.data.cityId
    wx.navigateTo({
      url: '/pages/webView/webview?url= ' + getApp().globalData.url+'stationList&distanceInfo=' + JSON.stringify(this.data.distanceInfo) + '&memberId=' + id + '&cityId=' + cityId
    })
  },
  //轮播跳转
  homeCarouselClick(e){
    let url=e.currentTarget.dataset.url
    if (url &&url.indexOf('/pages') != -1) {
      wx.navigateTo({
        url: url
      })
    }else{
      wx.navigateTo({
        url: '/pages/webView/webview?url=' + url
      })
    }
    
  },
  //热门跳转
  homeClick(e){
    
    let url = e.currentTarget.dataset.url
    if(url.substring(0,1)=="h"){
      wx.navigateTo({
        url: '/pages/webView/webview?url=' + url
      })
    }else{
      wx.navigateTo({
        url:  url
      })
    }
  },
  goShopItem(e){
    let id = e.currentTarget.dataset.item 
    wx.navigateTo({
      url: '/pages/shop/index?id='+id,
    })
  },
  getShopList(){
    wx.request({
      url: 'https://www.cyf.careoe.com:8030/wx/home/index',
      method:"get",
      success:res=>{
        this.setData({
          shopData: res.data.data.newGoodsList
        })
      }
    })
  },
  // 校验副卡弹窗
  receiveSub(memberId){
    let user = wx.getStorageSync("userInfo")
    api.receiveSubCardStatus({ memberId: user.id}).then(res=>{
      if(res.data.result){
        wx.showModal({
          content: '恭喜您获得一张亲属卡',
          showCancel:false,
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/cardPackage/cardPackage',
              })
            }
          }
        })
        wx.setStorageSync('indexSubCardState', 1)
      }
    })
  },
  registerActivityState(res){
    let that = this
    api.doRegisterActivity({ memberId:res.data.id}).then(res=>{
      api.getRegisterActivity({}).then(res => {
        if (res.data.result.couponList && res.data.result.couponList.length){
          let money = 0
          res.data.result.couponList.map(item=>{
            item.preAmount = math.divide(item.preAmount,100)
            money = math.plus(money, item.preAmount)
            item.minimumAmount = math.divide(item.minimumAmount,100)
            if (item.timeOut){
              item.date = tools.formatTime(new Date(item.timeOut))
            } else if (item.endDate){
              item.date = tools.formatTime(new Date(item.endDate))
            } else  {
              item.date = ""
            }
            switch (item.productId){
              case 1:
                item.productName = "柴油"
                break;
              case 2:
                item.productName = "汽油"
                break;
              case 3:
                item.productName = "非油"
                break;
              default :
                item.productName = "其他"
            }
            
          })
          that.setData({
            regesterData: res.data.result.couponList,
            showRegisterState: true,
            registerActivetyMoney: money
          })
        }  
      })
    })
  },
  distance(){
    getApp().copyCityId()
    wx.openLocation({
      latitude: Number(this.data.storeList.lat),
      longitude: Number(this.data.storeList.lot),
      scale: 18
    })
  },
  onShareAppMessage: function () {

  }
})
